package com.zhq.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhq.common.util.PageResult;
import com.zhq.entity.Goods;
import com.zhq.entity.Mer;
import com.zhq.mapper.GoodsMapper;
import com.zhq.service.MerService;
import com.zhq.service.GoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhq.vo.GoodsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
	@Autowired
	private MerService classesService;
	// 1. 分页查询
	@Override
	public PageResult<Goods> findByPage(Integer page, Integer pageSize) {
		// 1. 开始分页
		Page<Goods> page1 = this.page(new Page<>(page, pageSize));

		// 2. 封装分页结果
		return new PageResult<>(page1.getRecords(),page1.getTotal());
	}

	// 3. 条件带分页查询
	@Override
	public PageResult<Goods> search(Integer page, Integer pageSize, GoodsVO vo) {
		// 1. 进行分页带条件查询
		// 1.1 封装查询条件
		QueryWrapper<Goods> wrapper = new QueryWrapper<>();
		wrapper.like(StrUtil.isNotBlank(vo.getGoodsname()), "goodsname",  vo.getGoodsname() )
			   .like(StrUtil.isNotBlank(vo.getGoodssummary()), "goodssummary", vo.getGoodssummary())
			   .eq(vo.getMerid() != null && vo.getMerid() != 0, "merid", vo.getMerid());
		// 1.2 开始分页查询
		Page<Goods> page1 = this.page(new Page<>(page, pageSize), wrapper);
		// 1.3 处理学生所在班级名称
		page1.getRecords().forEach(st -> {
			Mer mer = classesService.getById(st.getMerid());
			st.setMername(mer.getMername());
		});
		// 2. 封装分页结果
		return new PageResult<>(page1.getRecords(),page1.getTotal());
	}

	// 添加学生
	@Override
	public boolean add(Goods goods) {
		return this.save(goods);
	}
}
